/* LwIP SNTP example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_log.h"
#include "esp_attr.h"

#include "lwip/err.h"
#include "lwip/apps/sntp.h"

static const char *TAG = "SNTP-APP";


void thread_timesync(void* args);


void sntp_app_init()
{
    ESP_LOGI(TAG, "Initializing SNTP");
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "pool.ntp.org");

    // Set timezone to China Standard Time
    setenv("TZ", "CST-8", 1);
    tzset();

    sntp_init();    

    // xTaskCreate(&thread_timesync, "thread_timesync", 2048, NULL, 5, NULL);



    // time_t now;
    // struct tm timeinfo;

    // while(1)
    // {

    //     char strftime_buf[64];

    //     // Set timezone to China Standard Time
    //     setenv("TZ", "CST-8", 1);
    //     tzset();
    //     time(&now);
    //     localtime_r(&now, &timeinfo);
    //     strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
    //     ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);

    //     vTaskDelay(1000);

    // }

}

// void thread_timesync(void* args)
// {
//     // wait for time to be set
//     time_t now = 0;
//     struct tm timeinfo = { 0 };
//     int retry = 0;
//     const int retry_count = 10;
//     while(timeinfo.tm_year < (2016 - 1900) && ++retry < retry_count) {
//         ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
//         vTaskDelay(2000 / portTICK_PERIOD_MS);
//         time(&now);
//         localtime_r(&now, &timeinfo);
//     }
//     sntp_stop();        


//     while(1)
//     {
//         sntp_enabled();
//         vTaskDelay(2000 / portTICK_PERIOD_MS);
//         sntp_stop();

//         vTaskDelay(60000 / portTICK_PERIOD_MS);        
//     }

//     vTaskDelete(NULL);
// }

void get_time(time_t *t,struct tm *tm)
{
    time_t temp_t;
    struct tm temp_tm;

    time(&temp_t);
    localtime_r(&temp_t, &temp_tm);

    if(t != NULL)
        *t = temp_t;
    
    if(tm != NULL)
        *tm = temp_tm;

}

void sntp_restart()
{
    sntp_stop();

    sntp_init();
}
